package com.erdos.upc.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.erdos.common.service.BaseCRUDService;
import com.erdos.upc.core.UpcUtil;
import com.erdos.upc.dao.GroupDao;
import com.erdos.upc.dao.UserDao;
import com.erdos.upc.entity.Group;
import com.erdos.upc.entity.Role;
import com.erdos.upc.entity.User;
import com.erdos.upc.service.GroupService;

public class GroupServiceImpl extends BaseCRUDService<Group> implements
		GroupService {
	private final Log logger = LogFactory.getLog(this.getClass());

	private UserDao userDao;

	private GroupDao groupDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	public GroupDao getGroupDao() {
		return groupDao;
	}

	public void setGroupDao(GroupDao groupDao) {
		this.groupDao = groupDao;
	}

	/**
	 * 完成创建用户组对象和关联集合对象的创建
	 */
	public Long insert(Group group) {
		// 调用Dao的insert方法创建用户对象本身
		Long sid=this.getGroupDao().insert(group);
		// 循环迭代每一个关联用户组，调用Dao层insertGroupUser插入关联记录
		if (group.getUsers() != null) {
			for (User user : group.getUsers()) {
				Map<String, Object> conditions = new HashMap<String, Object>();
				conditions.put("userSid", user.getSid());
				conditions.put("groupSid", group.getSid());
				conditions.put("createdBy", UpcUtil.getUpcUserPin());
				conditions.put("createdDt", new Date());
				conditions.put("version", 1);
				this.getGroupDao().insertGroupUser(conditions);
 
			}
		}
		// 循环迭代每一个关联用户组，调用Dao层insertGroupRole插入关联记录
		if (group.getRoles() != null) {
			for (Role role : group.getRoles()) {
				Map<String, Object> conditions = new HashMap<String, Object>();
				conditions.put("roleSid", role.getSid());
				conditions.put("groupSid", group.getSid());
				conditions.put("createdBy", UpcUtil.getUpcUserPin());
				conditions.put("createdDt", new Date());
				conditions.put("version", 1);
				this.getGroupDao().insertGroupRole(conditions);
			}
		}
		return sid;
	}

	/**
	 * 更新用户组对象和关联集合对象
	 */
	public void update(Group group) {
		// 调用Dao的update方法更新用户组group对象本身
		this.groupDao.update(group);
		// 通过group对象主键到通过Dao层查询到当前数据库关联的用户oldUsers集合对象和关联角色oldRoles集合对象
		Group oldGroup = this.groupDao.findByPrimaryKey(group.getSid());
		List<User> oldUsers = oldGroup.getUsers();
		List<Role> oldRoles = oldGroup.getRoles();
		// 传入group的新关联newUsers集合对象
		List<User> newUsers = group.getUsers();
		List<Role> newRoles = group.getRoles();
		// 需要新增的项目调用Dao层的insertGroupUser；需要删除的项目调用Dao层的deleteGroupUser
		List<Long> oldUserSids = new ArrayList<Long>();
		for (User user : oldUsers) {
			oldUserSids.add(user.getSid());
		}
		List<Long> newUserSids = new ArrayList<Long>();
		for (User user : newUsers) {
			newUserSids.add(user.getSid());
		}
		List<Long> inserUserSids = getInsertSids(newUserSids, oldUserSids);
		List<Long> deleteUserSids = getDeleteSids(oldUserSids, newUserSids);
		// 组用户更新
		this.updateGroupUsers(inserUserSids, deleteUserSids, group, this
				.getGroupDao());
		List<Long> oldRoleSids = new ArrayList<Long>();
		for (Role role : oldRoles) {
			oldRoleSids.add(role.getSid());
		}
		List<Long> newRoleSids = new ArrayList<Long>();
		for (Role role : newRoles) {
			newRoleSids.add(role.getSid());
		}
		List<Long> inserRoleSids = getInsertSids(newRoleSids, oldRoleSids);
		List<Long> deleteRoleSids = getDeleteSids(oldRoleSids, newRoleSids);
		// 组角色更新
		this.updateGroupRoles(inserRoleSids, deleteRoleSids, group, this
				.getGroupDao());
	}

	/**
	 * 执行组用户更新
	 * 
	 * @param inserUserSids
	 * @param deleteUserSids
	 * @param group
	 * @param groupDao
	 */
	private void updateGroupUsers(List<Long> inserUserSids,
			List<Long> deleteUserSids, Group group, GroupDao groupDao) {
		for (Long id : inserUserSids) {
			Map<String, Object> conditions = new HashMap<String, Object>();
			conditions.put("userSid", id);
			conditions.put("groupSid", group.getSid());
			conditions.put("createdBy", UpcUtil.getUpcUserPin());
			conditions.put("createdDt", new Date());
			conditions.put("version", 1);
			groupDao.insertGroupUser(conditions);
		}
		for (Long id : deleteUserSids) {			
			groupDao.deleteGroupUser(group.getSid(), id);
			
		}
	}

	/**
	 * 执行组角色更新
	 * 
	 * @param inserRoleSids
	 * @param deleteRoleSids
	 * @param group
	 * @param groupDao
	 */
	private void updateGroupRoles(List<Long> inserRoleSids,
			List<Long> deleteRoleSids, Group group, GroupDao groupDao) {
		for (Long id : inserRoleSids) {
			Map<String, Object> conditions = new HashMap<String, Object>();
			conditions.put("roleSid", id);
			conditions.put("groupSid", group.getSid());
			conditions.put("createdBy", UpcUtil.getUpcUserPin());
			conditions.put("createdDt", new Date());
			conditions.put("version", 1);
			groupDao.insertGroupRole(conditions);
		}
		for (Long id : deleteRoleSids) {
			groupDao.deleteGroupRole(group.getSid(), id);
		}
	}

	/**
	 * 获取要删除的sids
	 * 
	 * @param oldEntiySids
	 * @param newEntitySids
	 * @return
	 */
	private List<Long> getDeleteSids(List<Long> oldEntiySids,
			List<Long> newEntitySids) {
		List<Long> deleteSids = new ArrayList<Long>();
		for (Long id : oldEntiySids) {
			if (!newEntitySids.contains(id)) {
				deleteSids.add(id);
			}
		}
		return deleteSids;
	}

	/**
	 * 获取要插入的sids
	 * 
	 * @param newEntitySids
	 * @param oldEntiySids
	 * @return
	 */
	private List<Long> getInsertSids(List<Long> newEntitySids,
			List<Long> oldEntiySids) {
		List<Long> insertSids = new ArrayList<Long>();
		for (Long id : newEntitySids) {
			if (!oldEntiySids.contains(id)) {
				insertSids.add(id);
			}
		}
		return insertSids;
	}

	/**
	 * 删除用户组
	 */
	public int deleteByPrimaryKey(Long sid) {
		// 调用Dao的deleteGroupAllUsers删除该用户组所有用户关联记录
		this.getGroupDao().deleteGroupAllUsers(sid);
		// 调用Dao的deleteGroupAllRoles删除该用户组所有角色关联记录
		this.getGroupDao().deleteGroupAllRoles(sid);
		// 调用Dao的deleteByPrimaryKey删除该用户组记录
		return this.getGroupDao().deleteByPrimaryKey(sid);
	}

	/**
	 * 检查用户组名是否唯一
	 */
	public boolean checkNameExist(String sid, String name) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", name);
		logger.debug("lazy loading test...1");
		Group group = null;
		if (StringUtils.isNotEmpty(name)) {
			group = getGroupDao().findUniqueByParams(params);
		}
		if (StringUtils.isEmpty(sid)) {
			return group == null ? false : true;
		} else {
			if (group != null) {
				if (sid.equals(group.getSid().toString())) {
					return false;
				} else {
					return true;
				}
			} else {
				return false;
			}
		}
	}

	/* (non-Javadoc)
	 * @see com.hp.upc.service.GroupService#findAllUserGP()
	 */
	public Map<String, String> findAllUserGP() 
	{
		List<Group> allUserGroup = this.groupDao.findAll();
		
		Map<String,String> userGroupMap = new HashMap<String,String> ();
		
		if(allUserGroup == null||allUserGroup.size() == 0)
		{
			return userGroupMap;
		}
		
		
		for(int i=0;i<allUserGroup.size();i++)
		{
			userGroupMap.put(allUserGroup.get(i).getName(), allUserGroup.get(i).getDescription());
		}
		
		return userGroupMap;
	}

}
